import os
import requests
import json
import base64
import time
import math
import hashlib
import argparse
import uuid
import random

class UnitRequest(object):
    def __init__(self, url, path, app_id, app_key, TDEV = 0, timeout=600) -> None:
        super(UnitRequest, self).__init__()
        self.url = url
        self.path = path
        self.app_id = app_id
        self.app_key = app_key
        self.TDEV = TDEV
        self.timeout = timeout
    
    def __create_header(self):
        uid = str(uuid.uuid4())
        suid = ''.join(uid.split('-'))

        appid = self.app_id
        appKey = self.app_key
        appName = self.path.split('/')[1]

        for i in range(24 - len(appName)):
            appName += "0"
        capabilityname = appName
        # print(len(capabilityname))
        csid = appid + capabilityname + suid
        tmp_xServerParam = {
            "appid": appid,
            "csid": csid
        }
        # print(tmp_xServerParam)
        xCurTime = str(int(math.floor(time.time())) + self.TDEV)
        # print(xCurTime)
        xServerParam = str(base64.b64encode(json.dumps(
            tmp_xServerParam).encode('utf-8')), encoding="utf8")
        # xServerParam = str(base64.b64encode(json.dumps(tmp_xServerParam).encode('utf-8')))

        # turn to bytes
        xCheckSum = hashlib.md5(
         bytes(appKey + xCurTime + xServerParam, encoding="utf8")).hexdigest()
        # xCheckSum = hashlib.md5(bytes(appKey + xCurTime + xServerParam)).hexdigest()

        header = {
            # "appKey": appKey,
            "X-Server-Param": xServerParam,
            "X-CurTime": xCurTime,
            "X-CheckSum": xCheckSum,
            # "content-type": "application/x-www-form-urlencoded"
            'Content-Type': 'application/json'
        }

        user_agent_list = ["Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
                    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36",
                    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
                    "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15",]
        # print(random.choice(user_agent_list))
        user_agent = random.choice(user_agent_list)
        # print(user_agent)
        header['User-Agent'] = user_agent

        return header

    def send_request(self, request_body):
        try_num = 5
        while try_num > 0:
            try:
                response = requests.post(self.url+self.path, data=json.dumps(request_body), 
                                        headers=self.__create_header(), timeout=self.timeout)
                try_num = 0
                if response.status_code != requests.codes.ok: # 请求成功但是服务器失败
                    # print(response.content)
                    text = response.text.encode('utf-8').decode('unicode_escape')
                    # return None, None
                    return False, None, str(response.status_code)+"-"+text
                
                # response_data_str = response.text.encode('utf-8').decode('unicode_escape')
                response_data_str = response.text
                # print(response_data_str)
                response_data = json.loads(response_data_str)
                # print(response_data)
                if response_data['code'] == 200:
                    return True, response_data, None
                else:
                    return False, None, response_data
                
            except requests.exceptions.ConnectionError as ex:
                if try_num <= 0:
                    print("Failed to retrieve: " + self.url + self.path + "\n" + str(ex))
                    return False, None, "错误信息: 无法连接服务器"
                else:
                    print("连接失败，剩余尝试次数:{}".format(try_num))
                    try_num -= 1
                    time.sleep(0.5)